/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018/11/21 Time: 10:03
 *
 * 工作
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    Image,
    ScrollView,
    TouchableOpacity,
    TouchableHighlight, Platform, BackHandler, ToastAndroid, FlatList, Modal
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './orderScreen.Style';
import OffWorkView from "../../../component/OffWorkView/OffWorkView"
import {getDs} from "./Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import User from "../../../model/User/User";
import {getDs_R} from "../../job/WorkOrder/DepartmentalRepairOrderScreen/Actions";
import {DefaultTabBar} from "react-native-scrollable-tab-view";
import ScrollableTabView from "react-native-scrollable-tab-view";
import LoadingView from "../../../component/LoadingView/LoadingView";
import {Homepage} from "../../../router/Homepage"
import global from "../../../configuration/global";
import {createBottomTabNavigator} from "react-navigation";
import AntDesign from "react-native-vector-icons/AntDesign";
import {FONT_COLOR_SUB_TITLE,FONT_COLOR_TITLE} from "../../../constant/PHColors";
import {changeOrderStatus, changeSweepOrderStatus} from "../../../component/BottomButtonView/Actions";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplaySuccessMessage, doDisplayWarnMessage} from "../../../component/Message/Action";
import {whskMenuMain} from "../../login/LoginScreen/Actions";
import {retrieveOrderSweep} from "../roomCleanScreen/Actions";


class orderScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: ``,
        headerLeft: <View><Text style={{marginLeft:15,fontSize:18,color:FONT_COLOR_TITLE}}>工单</Text></View>,
        headerRight: <OffWorkView navigation={navigation}/>
    });

    //构造
    constructor(props) {
        super(props);

        this.state = {
            nav:this.props.navigation,
            tab: [],
            tab_unallocated: [],
            defaultInfo:{},
            refreshing:false,
            groupListVisiable:{"datasource_rush":true}, //组别打开或关闭
            alertModalVisible:false,//alert模态
            alertStr:{},
            alertData:{},
            redPoint:0,
        };

        this._navListener=[];

    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        const {navigation} = this.props;

        if (nextProps.onOrderScreenDs !== this.props.onOrderScreenDs && nextProps.onOrderScreenDs.fetchStatus === FetchStatus.Success) {
            let defaultInfo = nextProps.onOrderScreenDs;
            let tab = nextProps.onOrderScreenDs.tab;


            let redPoint = 0;
            for(let item of tab){
                let page_msg = {};
                redPoint = defaultInfo[item.value].length + redPoint
                page_msg.defaultMsg = defaultInfo[item.value];
                page_msg.pageNo = 1;
                page_msg.totalPage = 1;
                page_msg.recordNum = defaultInfo[item.value].length;
                this.state[item.value] = page_msg;
            }

            //导航栏刷新！！！！！
            global.Homepage.orderBarIcon = redPoint;
            if(this.props.navigation.isFocused()){
                navigation.navigate("Homepage",{"random":Math.random().toString()});
            }

            this.setState({
                redPoint:redPoint,
                tab: tab,
                defaultInfo:defaultInfo,
                refreshing:false,
            });

        }

        if (nextProps.onChangeSweepOrderStatus !== this.props.onChangeSweepOrderStatus && nextProps.onChangeSweepOrderStatus.fetchStatus === FetchStatus.Success) {
            if (nextProps.onChangeSweepOrderStatus.RETURN === ReturnStatus.Success) {
                doDisplaySuccessMessage(nextProps.onChangeSweepOrderStatus.MSG);
                let str = {};
                dispatch(getDs(JSON.stringify(str)));
            }else if(nextProps.onChangeSweepOrderStatus.RETURN === '-10'){
                this.setState({
                    alertModalVisible:true,
                    alertData:nextProps.onChangeSweepOrderStatus,
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onChangeSweepOrderStatus.MSG))
            }
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        let str = {};
        dispatch(getDs(JSON.stringify(str)));

        this._navListener = [this.props.navigation.addListener('didFocus', () => {
            let str = {};
            dispatch(getDs(JSON.stringify(str)));
        })]
    }

    componentWillMount() {
        this._navListener.forEach(sub => sub.remove());
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    onBackAndroid = () =>{
        if(this.props.navigation.isFocused()){//判断   该页面是否处于聚焦状态
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                BackHandler.exitApp();//直接退出APP
            }else{
                this.lastBackPressed = Date.now();
                ToastAndroid.show('再按一次退出应用', 1000);//提示
                return true;
            }
        }
    };

    render =()=> {
        let {dispatch,onOrderScreenDs} = this.props;
        if (JSON.stringify(this.state.defaultInfo)!=="{}") {
            return (
                <ScrollableTabView
                    tabBarUnderlineColor="#5897FE"
                    tabBarTextStyle={{
                        fontSize:18
                    }}
                    tabBarUnderlineStyle={{backgroundColor:'#5897FE',height:2}}
                    tabBarActiveTextColor="#5897FE"
                    style={styles.container}
                    renderTabBar={() => <DefaultTabBar />}
                >
                    {
                        this.renderAllocated()
                    }
                    {
                        this.renderUnallocated()
                    }
                </ScrollableTabView>
            )
        }else{
            return <LoadingView/>
        }


    }

    onRequestClose(){
        this.setState({
            alertModalVisible:false,
        })
    }

    //已分配工单
    renderAllocated = () => {
        let _this = this;
        let tab_info = this.state.tab;
        let redPointLeft = '我的工单('+this.state.redPoint+')';
        return(
            <View tabLabel={redPointLeft} style={styles.body} >
                {
                        (Number(this.state.redPoint) > 0)
                    ?
                        (
                            <SafeAreaView style={styles.body}>

                                <View style={styles.body}>
                                    {/*<View style={styles.headerContainer}>*/}
                                        {/*<Text style={styles.headerText}>*/}
                                            {/*共{_this.state.redPoint?_this.state.redPoint:'0'}张单*/}
                                        {/*</Text>*/}
                                    {/*</View>*/}
                                    <FlatList
                                        data = {['']}
                                        onRefresh = {this._onRefresh.bind(this)} //刷新操作
                                        refreshing = {_this.state.refreshing}
                                        renderItem={this._renderItem}
                                        ListFooterComponent={this._renderFooter()}
                                        onEndReachedThreshold={0.1}
                                        keyExtractor={(item, index) => index.toString()}
                                        onEndReached={this._onEndReached()}
                                    />
                                </View>
                                {/*alert-10模态框*/}
                                <Modal visible={this.state.alertModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                                    <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                                        this.onRequestClose();
                                    }}>
                                        <View style={styles.checkmodalContainer} >
                                            <View style={styles.checkModalBody}>
                                                <View style={styles.checkModalHeader}>
                                                    <Text style={styles.checkModalHeaderText}>
                                                        {this.state.alertData.MSG}
                                                    </Text>
                                                </View>
                                                <View style={styles.checkModalCenter}>
                                                    <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                                        this.setState({
                                                            alertModalVisible:false,
                                                        })
                                                    }}>
                                                        <Text style={{color:'black',fontSize:20}}>
                                                            取消
                                                        </Text>
                                                    </TouchableOpacity>
                                                    <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                                        this.setState({
                                                            alertModalVisible:false,
                                                        })
                                                        let str = this.state.alertStr;
                                                        str.arg={};
                                                        str.arg[this.state.alertData.checkbox]='yes';
                                                        dispatch(changeSweepOrderStatus(JSON.stringify(str)));
                                                    }}>
                                                        <Text style={{color:'white',fontSize:20}}>
                                                            继续
                                                        </Text>
                                                    </TouchableOpacity>
                                                </View>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                </Modal>
                            </SafeAreaView>
                        )
                    :
                        (
                            <SafeAreaView style={styles.container}>
                                <View  style={styles.windowCenter}>
                                    <View>
                                        <Text style={styles.headerText}>
                                            暂无任务
                                        </Text>
                                    </View>
                                    <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                                        this.setState({
                                            defaultInfo:{},
                                        },()=>{
                                            this.freshScreen();
                                        });
                                    }}>
                                        <View style={{marginTop:3}}>
                                            <Text style={[styles.headerText,{textDecorationLine:'underline',textDecorationStyle:'solid',fontSize:15}]}>
                                                点击刷新
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </SafeAreaView>
                        )
                }

            </View>
        )
    }

    //列表内容循环
    _renderItem = ({ item }) => {
        let _this=this;

        let datasource_rush = [];
        let datasource_clean = [];
        let datasource_check = this.state.defaultInfo.order_i_ftp;
        this.state.defaultInfo.order_w_ftp.map((item, index) => {
            if(item['ordertype']==="赶房"){
                datasource_rush.push(item)
            }else{
                datasource_clean.push(item)
            }
        })

        return (
            <View>
                {/*赶房*/}
                {
                    (datasource_rush.length>0) && (
                        <View>
                            <TouchableOpacity activeOpacity={1} onPress={() => {
                                let json = _this.state.groupListVisiable;
                                json['datasource_rush'] = !json['datasource_rush'];
                                _this.setState({
                                    groupListVisiable:json
                                })
                            }}>
                                <View style={styles.listBody}>
                                    <View style={styles.listTextBox}>
                                        <View style={styles.listLeftBox}>
                                            {
                                                this.state.groupListVisiable['datasource_rush'] ? <AntDesign name={'caretdown'} size={15} style={{color: FONT_COLOR_SUB_TITLE,marginTop: 2,marginLeft: 10}}/> : <AntDesign name={'caretright'} size={15} style={{color: FONT_COLOR_SUB_TITLE,marginTop: 3,marginLeft: 10}}/>
                                            }
                                            <Text style={styles[this.state.groupListVisiable['datasource_rush']?'listLeftBoxTextTrue':'listLeftBoxText']}>
                                                赶房
                                            </Text>
                                        </View>
                                    </View>

                                    <View style={styles.arrowBox}>
                                        <Text>0/{datasource_rush.length}</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                            {
                                (this.state.groupListVisiable['datasource_rush']) &&
                                (
                                    datasource_rush.map((item, index) => {
                                        return this._render_order_w(item, index)
                                    })
                                )
                            }
                        </View>
                    )
                }


                {/*清洁工单*/}
                {
                    (datasource_clean.length>0) && (
                        <View>
                            <TouchableOpacity activeOpacity={1} onPress={() => {
                                let json = _this.state.groupListVisiable;
                                json['datasource_clean'] = !json['datasource_clean'];
                                _this.setState({
                                    groupListVisiable:json
                                })
                            }}>
                                <View style={styles.listBody}>
                                    <View style={styles.listTextBox}>
                                        <View style={styles.listLeftBox}>
                                            {
                                                this.state.groupListVisiable['datasource_clean'] ? <AntDesign name={'caretdown'} size={15} style={{color: FONT_COLOR_SUB_TITLE,marginTop: 2,marginLeft: 10}}/> : <AntDesign name={'caretright'} size={15} style={{color: FONT_COLOR_SUB_TITLE,marginTop: 3,marginLeft: 10}}/>
                                            }
                                            <Text style={styles[this.state.groupListVisiable['datasource_clean']?'listLeftBoxTextTrue':'listLeftBoxText']}>
                                                清洁工单
                                            </Text>
                                        </View>
                                    </View>

                                    <View style={styles.arrowBox}>
                                        <Text>0/{datasource_clean.length}</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                            {
                                (this.state.groupListVisiable['datasource_clean']) &&
                                (
                                    datasource_clean.map((item, index) => {
                                        return this._render_order_w(item, index)
                                    })
                                )
                            }
                        </View>
                    )
                }


                {/*检查工单*/}
                {
                    (datasource_check.length>0)&&(
                        <View>
                            <TouchableOpacity activeOpacity={1} onPress={() => {
                                let json = _this.state.groupListVisiable;
                                json['datasource_check'] = !json['datasource_check'];
                                _this.setState({
                                    groupListVisiable:json
                                })
                            }}>
                                <View style={styles.listBody}>
                                    <View style={styles.listTextBox}>
                                        <View style={styles.listLeftBox}>
                                            {
                                                this.state.groupListVisiable['datasource_check'] ? <AntDesign name={'caretdown'} size={15} style={{color: FONT_COLOR_SUB_TITLE,marginTop: 2,marginLeft: 10}}/> : <AntDesign name={'caretright'} size={15} style={{color: FONT_COLOR_SUB_TITLE,marginTop: 3,marginLeft: 10}}/>
                                            }
                                            <Text style={styles[this.state.groupListVisiable['datasource_check']?'listLeftBoxTextTrue':'listLeftBoxText']}>
                                                检查工单
                                            </Text>
                                        </View>
                                    </View>

                                    <View style={styles.arrowBox}>
                                        <Text>0/{datasource_check.length}</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                            {
                                ( this.state.groupListVisiable['datasource_check']) &&
                                (
                                    datasource_check.map((item, index) => {
                                        return this._render_order_i(item, index)
                                    })
                                )
                            }
                        </View>
                    )
                }
            </View>
        )


    };

    //清洁工单
    _render_order_w = (item, index) => {
        let _this = this;
        return (
            <TouchableOpacity activeOpacity={0.8} key={"order_w"+index} onPress={() => {
                this.props.navigation.navigate('RoomStatusScreen',{room:item.room,button:'yes',authority:'清洁人',orderid:item.orderid,callBack:()=>_this.freshScreen()});
            }}>
                <View style={styles.boxBody}>
                    <View style={styles.imgBox}>
                        <Image
                            source={require('../../../resource/tabmenu/clean.png')}
                            style={styles.imageStyle}
                        />
                    </View>
                    <View style={styles.textBox}>
                        <View style={styles.top}>
                            <View style={styles.topLeft}>
                                <View style={styles.topLeftLine1}>
                                    <Text style={styles.topLeftLine1Text}>
                                        {item.room ? (item.room.length > 17 ? item.room.substr(0, 17) + "..." : item.room) : ""}
                                    </Text>
                                </View>
                                <View style={styles.topLeftLine2}>
                                    <Text style={styles.topLeftLine2Text}>
                                        {item.info ? (item.info.length > 17 ? item.info.substr(0, 17) + "..." : item.info) : ""}
                                    </Text>
                                </View>
                            </View>
                            <View style={styles.topRight}>
                                {
                                    _this.qckButton(item,"清洁人")
                                }
                            </View>

                        </View>



                        <View style={styles.bottom}>
                            <Text style={styles.bottomText}>
                                {item.crdate}
                            </Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    //检查工单
    _render_order_i = (item, index) => {
        let _this = this;
        return (
            <TouchableOpacity activeOpacity={0.9} key={"order_i"+index} onPress={() => {
                this.props.navigation.navigate('RoomStatusScreen',{room:item.room,button:'yes',authority:'检查人',orderid:item.orderid,callBack:()=>_this.freshScreen()});
            }}>
                <View style={styles.boxBody}>
                    <View style={[styles.imgBox,{borderWidth:0}]}>
                        <Image
                            source={require('../../../resource/tabmenu/check.png')}
                            style={[styles.imageStyle,{margin:0}]}
                        />
                    </View>
                    <View style={styles.textBox}>
                        <View style={styles.top}>
                            <View style={styles.topLeft}>
                                <View style={styles.topLeftLine1}>
                                    <Text style={styles.topLeftLine1Text}>
                                        {item.room ? (item.room.length > 17 ? item.room.substr(0, 17) + "..." : item.room) : ""}
                                    </Text>
                                </View>
                                <View style={styles.topLeftLine2}>
                                    <Text style={styles.topLeftLine2Text}>
                                        {item.info ? (item.info.length > 17 ? item.info.substr(0, 17) + "..." : item.info) : ""}
                                    </Text>
                                </View>
                            </View>
                            <View style={styles.topRight}>
                                {
                                    _this.qckButton(item,"检查人")
                                }
                            </View>

                        </View>



                        <View style={styles.bottom}>
                            <Text style={styles.bottomText}>
                                {item.crdate}
                            </Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    //未分配工单
    renderUnallocated=()=>{
        let _this = this;
        let tab_info = this.state.tab_unallocated
        return(
            <View tabLabel="未分配" style={styles.body} >
                {
                    (tab_info.length > 0)
                        ?
                        (
                            <SafeAreaView style={styles.body}>

                                <View style={styles.body}>
                                    <FlatList
                                        data = {tab_info}
                                        onRefresh = {this._onRefresh.bind(this)} //刷新操作
                                        refreshing = {_this.state.refreshing}
                                        renderItem={this._renderItem}
                                        ListFooterComponent={this._renderFooter()}
                                        onEndReachedThreshold={0.1}
                                        keyExtractor={(item, index) => index.toString()}
                                        onEndReached={this._onEndReached()}
                                    />
                                </View>
                                {/*alert-10模态框*/}
                                <Modal visible={this.state.alertModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                                    <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                                        this.onRequestClose();
                                    }}>
                                        <View style={styles.checkmodalContainer} >
                                            <View style={styles.checkModalBody}>
                                                <View style={styles.checkModalHeader}>
                                                    <Text style={styles.checkModalHeaderText}>
                                                        {this.state.alertData.MSG}
                                                    </Text>
                                                </View>
                                                <View style={styles.checkModalCenter}>
                                                    <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                                        this.setState({
                                                            alertModalVisible:false,
                                                        })
                                                    }}>
                                                        <Text style={{color:'black',fontSize:20}}>
                                                            取消
                                                        </Text>
                                                    </TouchableOpacity>
                                                    <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                                        this.setState({
                                                            alertModalVisible:false,
                                                        })
                                                        let str = this.state.alertStr;
                                                        str.arg={};
                                                        str.arg[this.state.alertData.checkbox]='yes';
                                                        dispatch(changeSweepOrderStatus(JSON.stringify(str)));
                                                    }}>
                                                        <Text style={{color:'white',fontSize:20}}>
                                                            继续
                                                        </Text>
                                                    </TouchableOpacity>
                                                </View>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                </Modal>
                            </SafeAreaView>
                        )
                        :
                        (
                            <SafeAreaView style={styles.container}>
                                <View  style={styles.windowCenter}>
                                    <View>
                                        <Text style={styles.headerText}>
                                            暂无任务
                                        </Text>
                                    </View>
                                    <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                                        this.setState({
                                            defaultInfo:{},
                                        },()=>{
                                            this.freshScreen();
                                        });
                                    }}>
                                        <View style={{marginTop:3}}>
                                            <Text style={[styles.headerText,{textDecorationLine:'underline',textDecorationStyle:'solid',fontSize:15}]}>
                                                点击刷新
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </SafeAreaView>
                        )
                }

            </View>
        )
    };

    qckButton = (info,authority)=>{
        let _this = this;

        html = (
            <View style={styles.topRightText} >
                <Text style={[styles.centerText,{color:'#c0c0c0'}]}>
                    {info.status}
                </Text>
            </View>
        );

        if(info.status!=="完成清洁" && info.status!=="完成检查"){
            html = (
                <View style={[styles.topRightButton,{backgroundColor:'#fff',borderColor:'#3cbc2c'}]} >
                    <Text style={[styles.centerText,{color:'#3cbc2c'}]}>
                        {info.status}
                    </Text>
                </View>
            );
        }

        this.props.onCacheButton.map((item, index) => {
            if(item.ordertype===info.ordertype && item.usertype===authority && item.status===info.status){
                let buttonList = item;
                if(JSON.stringify(buttonList)!=='{}'&&buttonList.operation!==""){
                    html = (
                        <TouchableOpacity  activeOpacity={1} onPress = {()=>{
                            _this.qckClick(info.orderid,buttonList.operation.split(",")[0]);
                        }}>
                            <View style={styles.topRightButton} >
                                <Text style={styles.centerText}>
                                    {_this.getQckButtonName(buttonList.operation.split(",")[0])}
                                </Text>
                            </View>
                        </TouchableOpacity>
                    )
                }
            }
        });

        return html
    };

    getQckButtonName(operation){
        let text = operation;
        if(operation==="开始清洁"){
            text = "开始清洁"
        }else if(operation==="完成清洁"){
            text = "完成"
        }else if(operation==="完成检查"){
            text = "完成检查"
        }
        return text
    };


    qckClick(orderid,value){
        let {dispatch} = this.props;

        let str = {"whsk_Order_Sweep_event":{"orderid":orderid},"whsk_Order_event":{"operation":value}}
        dispatch(changeSweepOrderStatus(JSON.stringify(str)));

    }

    //下拉刷新,更改状态，重新获取数据
    _onRefresh(){
        this.setState({
            refreshing:true,
        },()=>{
            let {dispatch} = this.props;

            let str = {};
            dispatch(getDs(JSON.stringify(str)));
        });
    }

    _renderFooter=()=>{
        return (
            <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                    {/*没有更多数据了*/}
                </Text>
            </View>
        );
    }

    _onEndReached=()=>{
        return ;
    }

    freshScreen=()=>{
        let {dispatch} = this.props;

        let str = {};
        dispatch(getDs(JSON.stringify(str)))
    }

}

const props = state => {
    return {
        onOrderScreenDs: state.onOrderScreenDs,
        onCacheButton: state.onCache.buttonlist,
        onChangeSweepOrderStatus:state.onChangeSweepOrderStatus,
    }
};

export default orderScreen = connect(props)(orderScreen);
